<template>
  <div class="m-4">
    <BasicTable @register="registerTable">
      <template #headerTop>
        <Alert v-if="checkedKeys.length > 0" type="info" show-icon style="position: relative">
          <template #message>
            <div>
              <span>已选中{{ checkedKeys.length }}条记录</span>
              <div style="position: absolute; top: 4px; right: 10px">
                <Tooltip title="删除">
                  <a-button type="text" @click="handleSelectedDelete">
                    <Icon :icon="ICON.DELETE" color="#0960bd" />
                  </a-button>
                </Tooltip>
              </div>
            </div>
          </template>
        </Alert>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'ant-design:retweet-outlined',
                tooltip: {
                  title: '再次通知',
                  placement: 'top',
                },
                onClick: notifyAgain.bind(null, record),
              },
              {
                icon: 'ic:baseline-delete',
                tooltip: {
                  title: '删除',
                  placement: 'top',
                },
                onClick: deleteOneSend.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <!--发送通知弹窗-->
    <SendNotificationsModal @register="registerModal" @close-flag="closeFlag" />
  </div>
</template>

<script lang="ts" setup>
  import Icon from '/@/components/Icon/src/Icon.vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { sentColumns } from '../data/notification.data';
  import { useModal } from '/@/components/Modal';
  import { tableFormStyleSetting, tableStyleSetting } from '/@/settings/thingsBoardDesign';
  import { onMounted, ref } from 'vue';
  import { getRequestsList, deleteTheRequests } from '/@/api/thingsborad/notification/notification';
  import SendNotificationsModal from './SendNotificationsModal.vue';
  import { Tooltip, Alert } from 'ant-design-vue';
  import dayjs from 'dayjs';
  import { ICON } from '/@/enums/iconEnum';
  import { useMessage } from '/@/hooks/web/useMessage';
  // 消息通知框
  const { createConfirm } = useMessage();
  //多选数组
  let checkedKeys = ref<any>([]);
  onMounted(() => {
    setProps({});
  });
  // 初始化发送通知弹窗
  const [registerModal, { openModal, setModalProps }] = useModal();

  //表格初始化
  const [registerTable, { reload, setProps }] = useTable({
    columns: sentColumns,
    ...tableStyleSetting,
    useSearchForm: false,
    api: getRequestsList,
    beforeFetch: (val) => {
      return {
        page: val.page - 1,
        pageSize: val.pageSize,
        sortOrder: val.order == 'ascend' ? 'ASC' : 'DESC',
        sortProperty: 'createdTime',
        textSearch: val.name,
      };
    },
    afterFetch: (res) => {
      if (res.length === 0) {
        return [];
      }
      return res.map((item: Recordable) => ({
        createdTime: dayjs(item.createdTime).format('YYYY-MM-DD HH:mm:ss'),
        status: item.status,
        deliveryMethods: item.deliveryMethods.join(','),
        template: item.templateName,
        id: item.id.id,
        info: item,
      }));
    },
    fetchSetting: {
      pageField: 'page',
      sizeField: 'pageSize',
      listField: 'data',
      totalField: 'totalElements',
    },
    formConfig: {
      layout: 'horizontal',
      showAdvancedButton: false,
      submitFunc: async () => {
        reload();
      },
      ...tableFormStyleSetting,
      actionColOptions: {
        md: { span: 8, offset: 16 },
        lg: { span: 6, offset: 16 },
        xl: { span: 4, offset: 16 },
        xxl: { span: 4, offset: 16 },
      },
    },
    rowKey: 'id',
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: checkedKeys,
      onSelect: onSelect,
      onSelectAll: onSelectAll,
    },
  });
  // 多选删除
  const handleSelectedDelete = () => {
    createConfirm({
      iconType: 'info',
      title: `确定要删除      '${checkedKeys.value.length}'     个请求吗？`,
      content: '请注意：确认后，及其所有相关数据将不可恢复。',
      onOk: async () => {
        for (const item of checkedKeys.value) {
          await deleteTheRequests(`/${item}`);
        }
        setProps({
          useSearchForm: false,
        });
        reload();
        checkedKeys.value = [];
      },
    });
  };

  function closeFlag() {
    reload();
  }
  // 多选
  function onSelect(record, selected) {
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, record.id];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => id !== record.id);
    }
  }
  // 全选
  function onSelectAll(selected, _selectedRows, changeRows) {
    const changeIds = changeRows.map((item) => item.id);
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, ...changeIds];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => {
        return !changeIds.includes(id);
      });
    }
  }
  //已发送再次通知
  function notifyAgain(record: Recordable) {
    setModalProps({
      width: 800,
    });
    openModal(true, record);
  }
  // 删除单条信息
  async function deleteOneSend(record: Recordable) {
    createConfirm({
      iconType: 'info',
      title: `您确定要删除该请求吗？`,
      content: '请注意，在确认后，将无法恢复。',
      onOk: async () => {
        await deleteTheRequests(`/${record.id}`);
        setProps({
          useSearchForm: false,
        });
        reload();
      },
    });
  }
</script>
